package com.billion.netty.utils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class NettyUtil {
    /**
     * bytebuf转string
     * @param msg
     * @return
     */
    public static String hexByteStr(ByteBuf msg) {
        String HEXES = "0123456789ABCDEF";
        byte[] req = new byte[msg.readableBytes()];
        msg.readBytes(req);
        final StringBuilder hex = new StringBuilder(2 * req.length);

        for (int i = 0; i < req.length; i++) {
            byte b = req[i];
            if(i>0){
                hex.append(" ");
            }
            hex.append(HEXES.charAt((b & 0xF0) >> 4))
                    .append(HEXES.charAt((b & 0x0F)));
        }
        return new String(hex);
    }

    /**
     * 根据连接对象获取ip
     * @param ctx
     * @return
     */
    public static String getHostAddress(ChannelHandlerContext ctx){
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        return insocket.getAddress().getHostAddress();
    }

    /**
     * 根据连接对象获取ip
     * @param ctx
     * @return
     */
    public static InetSocketAddress getRemoteAddress(ChannelHandlerContext ctx){
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        return insocket;
    }
}
